using AdminApiTemplate.Api.Filters;
using AdminApiTemplate.Api.Helpers;
using AdminApiTemplate.Cache;
using AdminApiTemplate.Common.Helpers;
using AdminApiTemplate.Services.SysConfig;
using AdminApiTemplate.Tasks;
using AdminApiTemplate.ThirdParty.Redis;
using System.Data;
using System.Data.Common;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "AdminApiTemplate.Api", Version = "v1" });
    //var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    //var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    //c.IncludeXmlComments(xmlPath, true);

    var file = Path.Combine(AppContext.BaseDirectory, "AdminApiTemplate.Api.xml");
    var path = Path.Combine(AppContext.BaseDirectory, file);
    c.IncludeXmlComments(path, true);
    c.OrderActionsBy(o => o.RelativePath);

    var modelsfile = Path.Combine(AppContext.BaseDirectory, "AdminApiTemplate.Services.xml");
    var modelspath = Path.Combine(AppContext.BaseDirectory, modelsfile);
    c.IncludeXmlComments(modelspath, true);

    var commonfile = Path.Combine(AppContext.BaseDirectory, "AdminApiTemplate.Common.xml");
    var commonpath = Path.Combine(AppContext.BaseDirectory, commonfile);
    c.IncludeXmlComments(commonpath, true);

    var Aggregatefile = Path.Combine(AppContext.BaseDirectory, "AdminApiTemplate.Aggregates.xml");
    var Aggregatepath = Path.Combine(AppContext.BaseDirectory, Aggregatefile);
    c.IncludeXmlComments(Aggregatepath, true);
});

//允许跨域访问
builder.Services.AddCors(options =>
{
    options.AddPolicy("cors", (builder) =>
    {
        builder = builder.SetIsOriginAllowed((host) => true);
        builder.AllowAnyMethod()
           .AllowAnyHeader()
           .AllowCredentials();
    });
});

var defaultConnection = builder.Configuration.GetConnectionString("DefaultConnection");
defaultConnection = EncryptHelper.DESDecrypt(defaultConnection, "20230228");
builder.Services.AddScoped<IDbConnection, DbConnection>(x => { return new MySql.Data.MySqlClient.MySqlConnection(defaultConnection); });

var sqlHelper = new MySqlHelper(defaultConnection);
CacheHelper.DefaultQuery = sqlHelper;

var sql = "SELECT KeyName,Val from SysConfig";
var configs = sqlHelper.GetList<SysConfigDto>(sql);
var cacheItems = configs.Select(o => new SysConfigItem
{
    KeyName = o.KeyName,
    Val = o.Val
}).ToList();
ConfigHelper.Init(cacheItems);

var host = ConfigHelper.GetSysConfig<string>("Redis:Host", "");
var port = ConfigHelper.GetSysConfig<int>("Redis:Port", 6379);
var pass = ConfigHelper.GetSysConfig<string>("Redis:Pass", null);
if (!string.IsNullOrEmpty(host))
{
    RedisHelper.Init("admin", host, port, pass);
}

var startTask = WebHelper.GetWebsiteConfig("StartTask");
if (!string.IsNullOrEmpty(startTask))
{
    var taskHelper = new BaseTaskHelper(sqlHelper);
    Task.Run(() =>
    {
        try
        {
            taskHelper.Run();
        }
        catch (Exception ex)
        {
            LogHelper.WriteError(ex.ToString());
        }
    });
}

var assembly = Assembly.Load("AdminApiTemplate.Services");
var types = assembly.GetTypes();
var services = types.Where(w => w.Name.EndsWith("Service"));
foreach (var type in services)
{
    builder.Services.AddScoped(type);
}

var assembly2 = Assembly.Load("AdminApiTemplate.Aggregates");
var types2 = assembly2.GetTypes();
var services2 = types2.Where(w => w.Name.EndsWith("Composite"));
foreach (var type in services2)
{
    builder.Services.AddScoped(type);
}

builder.Services.AddMvc(option =>
{
    option.Filters.Add<HttpGlobalExceptionFilter>();
    option.Filters.Add<ProcessActionFilter>();
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{

}
app.UseSwagger();
app.UseSwaggerUI();
app.UseStaticFiles();

app.UseAuthorization();

app.UseCors("cors");
app.Use(async (context, next) =>
{
    context.Request.EnableBuffering();
    await next.Invoke();
});

app.MapControllers();

app.Run();
